import React, { FC, useEffect, useRef, useState } from 'react'
import { Button, Card, Descriptions, DatePicker, Form, Input, message, Modal, Select, Table, Tag, Tooltip, Drawer } from "antd";
import './index..css'
import { ExclamationCircleOutlined, SearchOutlined } from "@ant-design/icons";
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";


// @ts-ignore
import shortid from 'shortid'
import DeleteOutlined from '@ant-design/icons/lib/icons/DeleteOutlined';
import EditOutlined from '@ant-design/icons/lib/icons/EditOutlined';
import SyncOutlined from '@ant-design/icons/lib/icons/SyncOutlined';
import XLSX from "xlsx";
import { log } from 'console';
import exportExcel from '@/utils/exportExcel';
const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const Unbinding: FC = () => {
    return <div className={'students-operations'}>
        <Search />
    </div>
}

const Search: FC = () => {
    const input = useRef<any>('')
    const [switchover, setSwitchover] = useState<any>('1')
    const [switchovers, setSwitchovers] = useState<any>()
    const [loadings, setLoadings] = useState<boolean[]>([false,false]);
    const [timeData, setTimeData] = useState<any>({
        pageStart: 1,
        pageSize: 9,
        startDate: '',
        endDate: '',
    })
    const [timeValue, settimeValue] = useState<any>({ start: '', end: '' })
    const [tableData, setTableData] = useState([])
    const {
        data,
        run,
        refresh
    } = useRequest((() => fetchRequest(url.GET_IMEI_LIST, {
        imei: input.current!.input.value

    })), {
        manual: true,
        onSuccess: (res) => {
            if (!res.success) {
                message.error(res.errorMsg)
            }
            return res
        }
    })
    // 请求表格数据
    async function getVideoList(params: any) {
        try {
            const json = await fetchRequest(url.GRT_COLLEGELIST, params);
            if (json.success) {
                setTableData(json.data)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    // 发送表格数据请求传参
    const getTableData = useRequest(getVideoList, {
        manual: true,
        loadingDelay: 200
    })
    const ButClick = (data: any) => {
        if (data === '3') {
            setSwitchovers(switchover)
            setSwitchover(data)
            showDrawer()
        }
        setSwitchover(data)
    }
    // 时间改变方法
    const timeChange = (date: any, dateString: any) => {
        setTimeData({
            ...timeData, startDate: dateString[0], endDate: dateString[1]
        })
        settimeValue(date)
    }
    const handleTime = () => {
        settimeValue({ start: '', end: '' })
        getTableData.run({
            pageStart: 1,
            pageSize: 9,
            startDate: '',
            endDate: '',
        })
    }
    useEffect(() => {
        if (switchover === '2') getTableData.run(timeData)
        return () => {
        }
    }, [switchover])
    // 搜索
    const search = () => {
        getTableData.run(timeData)
    }
    const [addVisible, setAddVisible] = useState(false);
    const showDrawer = () => {
        setAddVisible(true);
    };

    const onClose = () => {
        setAddVisible(false);
        setImportTable([])
        setImportTables([])
    };

    // 批量换卡表格头
    const whiteCardTable :any[]= [
        {
            title: 'imei号',
            dataIndex: 'imei',
            key: 'imei',
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
        },
        {
            title: '旧白卡号',
            dataIndex: 'oldWhiteCard',
            key: 'oldWhiteCard',
        },
        {
            title: '新白卡号',
            dataIndex: 'newWhiteCard',
            key: 'newWhiteCard',
        },
        {
            title:'错误提示',
            render:(record: any)=>{
                return <span style={{color:record.error == "1" ? '#ff4d4f' : '#d9d9d9'}}>{record.error == "1" ? "信息不能为空" : ""}</span>
            }
        }
    ]
    // 批量换卡表格头
    const whiteCardTables :any[]= [
        {
            title: 'imei号',
            dataIndex: 'imei',
            key: 'imei',
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
        },
        {
            title: '旧白卡号',
            dataIndex: 'oldWhiteCard',
            key: 'oldWhiteCard',
        },
        {
            title: '新白卡号',
            dataIndex: 'newWhiteCard',
            key: 'newWhiteCard',
        },
        {
            title:'错误提示',
            render:(record: any)=>{
                return <span style={{color:!record.isReplace  ? '#ff4d4f' : '#11e516'}}>{record.remark}</span>
            }
        }
    ]
    const [importTable, setImportTable] = useState<any[]>([]) // 导入的导入的TABLE
    const [importTables, setImportTables] = useState<any[]>([]) // 导入的导入的TABLE
    const [upData,setUpData] = useState<boolean>(true)
    // 上传白卡号文件
    const fileChange = async( e:any) => {     
        const file = e.target.files?.[0]
        if (file) {
            const list = await handleExcelFile<any[]>(file)
            
            const tempList = list.map(item => ({
                imei: item['imei号'],
                studentId : item['学号'],
                oldWhiteCard: item['旧白卡号'],
                newWhiteCard: item['新白卡号'],
                rowNum: item.__rowNum__,
            }))
            tempList.forEach((item:any) =>{
                for (const key in item) {
                   if(!item[key]){
                    setUpData(true)
                       item.error = 1
                   }
                }
            })
            setUpData(false)
            setImportTable(tempList)
        }
    }
    const handleExcelFile = <T,>(file: File) => {
        let reader = new FileReader();  // 使用 FileReader 读取数据

        return new Promise<T>(((resolve, reject) => {

            reader.onload = function (e) {  // 数据读取完成后的回调函数
                try {

                    let workbook = XLSX.read(e.target?.result, { type: 'binary' })
                    let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
                    let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
                    let res = XLSX.utils.sheet_to_json(worksheet) as unknown as T;  // 使用 utils 里的方法转换内容为便于使用的数组
                    resolve(res)
                } catch (e) {
                    message.error("数据异常！");
                    reject(e)
                }
            };
            reader.readAsBinaryString(file);  // 读取数据

        }))
    }


    //  发送请求 拿到表格数据
    const getAbnormal = async (params: any) => {
        setLoadings([true,false])
        try {
            const json = await fetchRequest(url.CET_CONSUMEREPLACEWHITECARD, params);
            if (json.success) {
                setImportTables(json.data)
                setLoadings([false,false])
            } else {
                setLoadings([false,false])
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            setLoadings([false,false])
            message.error(error.message)
        }
    }
    // 发送表格数据请求传参
    const getTableDatas = useRequest(getAbnormal, {
        manual: true,
        loadingDelay: 200
    })
    const importClick = () => {
        !upData ? getTableDatas.run(importTable):message.error("请上传正确白卡数据");

    }
    const leadingOut = async () =>{
        setLoadings([false,true])
        if(importTables.length >0) {
            const data = importTables.map((item: any) => {
                const tempItem = {}
                tempItem['imei号'] = item.imei
                tempItem['学号'] = item.studentId
                tempItem['旧白卡号'] = item?.oldWhiteCard
                tempItem['新白卡号'] = item.newWhiteCard
                tempItem['错误提示'] = item.remark
                tempItem['上传结果'] = item.isReplace ?'成功':'失败'
                return tempItem
            })
            exportExcel(data, '白卡批量换卡模板.xlsx')
            setLoadings([false,false])
        }else message.error("请上传白卡数据在导出")
        setLoadings([false,false])
    }

     
    const cardType = data?.data?.cardType === 1 ? '智能学生证' : '普通白卡'
    const cardColor = data?.data?.cardType === 1 ? '#40a9ff' : '#d9d9d9'
    const ware = data?.data?.isWarehousing === 1 ? '已入库' : '未入库'
    return <>
        <div className="search-form">
            <div>
                <Button type={switchover === '1' ? "primary" : 'link'} onClick={() => ButClick('1')}
                    style={{ marginRight: '10px' }}>学生证运维</Button>
                <Button type={switchover === '2' ? "primary" : 'link'} style={{ marginRight: '10px' }} onClick={() => ButClick('2')}>学校整理</Button>
                {/* <Button type={switchover === '3' ? "primary" : 'link'} onClick={() => ButClick('3')}>批量换卡</Button> */}
            </div>
            {
                switchover === '1' ?
                    <div className='search-right'>
                        <div>
                            <span>imei卡号：</span>
                            <Input style={{ width: 300 }} ref={input} />
                        </div>
                        <Button type={'primary'} className={'search-form-btn'} icon={<SearchOutlined />} onClick={() => {
                            if (!input.current!.input.value) {
                                message.error('请输入imei卡号')
                                return
                            }
                            run()
                        }}>搜索</Button></div>
                    : <div className='search-right'>
                        <div>
                            <span>时间：</span>
                            <RangePicker onChange={timeChange} value={timeValue} />
                        </div>
                        <Button type={'primary'} className={'search-form-btn'} icon={<SearchOutlined />} onClick={search}>搜索</Button>
                        <Button icon={<SyncOutlined />} onClick={handleTime} style={{ marginLeft: '8px' }}>重置</Button></div>

            }
        </div>
        {switchover === '1' && data?.data ?
            <Card title="学生证信息" className={'table-form'} extra={<Tag color={cardColor}>{cardType}</Tag>}>
                <Descriptions>
                    <Descriptions.Item label="入库状态">{ware}</Descriptions.Item>
                    <Descriptions.Item label="厂商名称">{data?.data.vendorName}</Descriptions.Item>
                    <Descriptions.Item label="入库时间">{data?.data.warehousingTime}</Descriptions.Item>
                </Descriptions>
            </Card> : null}
        {
            switchover === '1' ?
                <ATable data={data?.data?.guardianUnBindVos} refresh={refresh} /> : switchover === '2' ?
                    <ClearUp tableData={tableData} getTableData={getTableData} timeData={timeData} /> : null
        }
        <Drawer width="60%" title="批量换卡" visible={addVisible} onClose={onClose} destroyOnClose>
            <div className={'import-item'}>
                导入模板: <span className={'import-val'}><a href={require('@/excel/白卡批量换卡模板.xlsx')} download>模板下载</a></span>
            </div>
            <div className={'import-item'}>
                上传文件: <span className={'import-val'}>
                    <input type='file' accept='.xlsx, .xls'
                        onChange={(e) => fileChange(e)} ref={input} />
                </span>
            </div>
            <div className={'import-item'}>
                数据预览：
            </div>
            <div className={'import-item'}>
                <Table columns={whiteCardTable} rowKey={(record: any) => record.rowNum} 
                    pagination={{ hideOnSinglePage: true, simple: true, pageSize: 4,  }}
                    dataSource={importTable}
                />
            </div>
            <div style={{ paddingBottom: 5 }}>
                <Button  type="primary" onClick={importClick}  loading={loadings[0]} htmlType="submit">提交</Button>
                <Button  style={{ marginLeft: 20 }} type="primary" onClick={leadingOut} loading={loadings[1]} htmlType="submit">导出</Button>
              </div>
            <div className={'import-item'}>
                错误提示:
            </div>
            <div className={'import-item'}>
                <Table columns={whiteCardTables} rowKey={(record: any) => record.newWhiteCard} 
                    pagination={{ hideOnSinglePage: true, simple: true, pageSize: 4,  }}
                    dataSource={importTables}
                />
            </div>
        </Drawer>
    </>
}

// 学校整理板块
const ClearUp = (props: any) => {
    const { tableData, getTableData, timeData } = props
    const [visible, setVisible] = useState(false)
    const [sceneValue, setSceneValue] = useState([])
    const [dataId, setDataId] = useState({})
    const [paramsData, setparamsData] = useState({ pageStart: 1, pageSize: 9 })
    //  存放校区名称数据数组
    const [collegeAreaList, setCollegeAreaList] = useState<any[]>([]);

    //  校区名称循环下拉框数据
    const collegeAreaOption = collegeAreaList?.map((d: any, index: number) => <Option value={d.collegeId}
        key={index}>{d.collegeName}</Option>);
    const columns: any[] = [
        {
            title: '学校',
            dataIndex: 'collegeName',
            key: 'collegeName',
        },
        {
            title: 'IMEI号码',
            dataIndex: 'imei',
            key: 'imei',
        },
        {
            title: '绑定日期',
            dataIndex: 'createdAt',
            key: 'createdAt;',
        },

        {
            title: "操作",
            render: (record: any) => <span onClick={e => e.stopPropagation()}>
                <Tag className="tags-hover" color="#00BFFF"
                    onClick={() => seteditVisible(record)}
                    icon={<EditOutlined />}>修改</Tag>
            </span>
        }
    ]
    const school = { 'index': 1, 'num': 999999, collegeName: '' }
    // 修改
    const seteditVisible = (value: any) => {
        getSchoolOrganizationRequest(school)
        form.resetFields();
        setVisible(true)
        setDataId(value.imei)
    }


    //  获取校区名称
    async function getSchoolOrganizationRequest(val: any) {
        try {
            const json = await fetchRequest(url.GET_SEARCHCOLLEGE, val);
            if (json.success) {
                message.destroy();
                setCollegeAreaList(json.data.rows);
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message);
        }
    }

    // // 请求表格数据
    // async function getVideoList(params: any) {
    //     try {
    //         const json = await fetchRequest(url.GRT_COLLEGELIST, params);
    //         if (json.success) {
    //             setTableData(json.data)
    //         } else {
    //             message.destroy();
    //             message.error(json.error)
    //         }
    //     } catch (error: any) {
    //         message.destroy();
    //         message.error(error.message)
    //     }
    // }

    // // 发送表格数据请求传参
    // const getTableData = useRequest(getVideoList, {
    //     manual: true,
    //     loadingDelay: 200
    // })

    useEffect(() => {
        // getTableData.run(paramsData)
        return () => {
        }
    }, [])

    // 控制显影
    const onClose = (event: any) => {
        // 阻止冒泡行为
        if (event.target.className === 'Divname') {
            setVisible(false);
        }
    };

    // 修改方法
    async function getupdateCollege(params: any) {
        try {
            const json = await fetchRequest(url.GRT_UPDATECOLLEGE, params);
            if (json.success) {
                message.success("修改成功!");
                if (tableData.rows.length === 1 && paramsData.pageStart !== 1) {
                    getTableData.run({ ...timeData, ...paramsData, pageStart: paramsData.pageStart - 1 })
                } else {
                    getTableData.run({ ...timeData, ...paramsData })
                }

                setVisible(false);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    // 发送修改请求
    const getAmend = useRequest(getupdateCollege, {
        manual: true,
        loadingDelay: 200
    })

    const layout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    };
    const tailLayout = {
        wrapperCol: { offset: 5, span: 14 },
    };

    // 确认按钮回调
    function onFinish(value: any) {
        const data = collegeAreaList?.find((d: any) => {
            return d.collegeId === value.collegeId
        })
        getAmend.run({ ...data, imei: dataId })
    }

    // 更改页码跳转
    const pageChange = (page: any) => {
        setparamsData({ ...paramsData, pageStart: page })
        getTableData.run({ ...paramsData, ...timeData, pageStart: page })
    }

    // 输入框改变事件
    const handleSearch = (value: any) => {
        if (value) {
            getSchoolOrganizationRequest({ ...school, collegeName: value })
        } else {
            setCollegeAreaList([]);
        }
    }

    const handleChange = (value: any) => {
        setSceneValue(value)
    }
    const [form] = Form.useForm()
    return (
        <>
            <Table className={'table-form'}
                pagination={{
                    current: tableData['page'],
                    hideOnSinglePage: true, simple: true, pageSize: tableData['size'],
                    total: tableData['total'], onChange: pageChange
                }}
                columns={columns} rowKey="id" dataSource={tableData['rows']} loading={getTableData.loading} />
            {
                visible ? <div className='Divname' onClick={onClose}>
                    <div className='tableCenter'>
                        <Form form={form} {...layout} onFinish={onFinish} initialValues={
                            {}}>
                            <Form.Item label="学校" name="collegeId" rules={[{ required: true, message: '必须要选择学校' }]}>
                                <Select placeholder="请选择学校名称"
                                    onSearch={handleSearch}
                                    showSearch
                                    value={sceneValue}
                                    defaultActiveFirstOption={false}
                                    showArrow={false}
                                    filterOption={false}
                                    onChange={handleChange}
                                    notFoundContent={null}

                                >
                                    {collegeAreaOption}
                                </Select>
                            </Form.Item>
                            <Form.Item {...tailLayout}>
                                <Button type="primary" htmlType="submit">提交</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div> : null
            }
        </>
    )
}

const ATable: FC<{ data: any, refresh: any }> = ({ data, refresh }) => {
    const columns: any[] = [

        {
            title: '学生姓名',
            dataIndex: 'studentName',
            key: 'studentName',
        },
        {
            title: '监护人电话号码',
            dataIndex: 'guardianPhone',
            key: 'guardianPhone',
        },
        {
            title: '是否为主监护人',
            dataIndex: 'isGuardian',
            key: 'createdBy',
            render: (text: string) => {
                const color = text == "1" ? '#ff4d4f' : '#d9d9d9'
                return <Tag color={color}>{text == "1" ? "是" : "否"}</Tag>
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt;',
        },


        {
            title: '操作',
            render: (item: any) => <>
                <Tooltip placement="topLeft" title="数据按正常流程推送至厂商进行解绑" arrowPointAtCenter>
                    <Tag color={'rgb(16, 142, 233)'} onClick={() => undoing(item, 1)}>推送解绑</Tag>
                </Tooltip>
                <Tooltip placement="topLeft" title="直接失效校园翼卡通绑定状态" arrowPointAtCenter>
                    <Tag color={'rgb(16, 142, 233)'} onClick={() => undoing(item, 2)}>强行解绑</Tag>
                </Tooltip>
            </>
        }
    ]

    const {
        run,
    } = useRequest(((params) => fetchRequest(url.UNBIND, params)), {
        manual: true,
        onSuccess: async (res) => {
            if (res.success) {
                message.success(res.data)
            } else {
                message.error(res.errorMsg)
            }
        }
    })


    const undoing = async (item: any, type: any) => {

        confirm({
            title: '解绑',
            icon: <ExclamationCircleOutlined />,
            content: '确认解绑吗?',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            async onOk() {
                await run({
                    id: item.id,
                    unBindType: type
                })
                await refresh()
            },
            onCancel() {
            },
        });


    }
    return <>

        <Table className={'table-form'} columns={columns} rowKey="id" dataSource={data} />
    </>
}

export default Unbinding
